package com.siyoumi.app.netty.entity;

import com.siyoumi.component.XBean;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XReturn;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

//信息实体
@Slf4j
public class NettyMsg
        extends XReturn {
    public NettyMsg(@NonNull Integer errcode, String errmsg, HashMap<String, Object> data) {
        if (data == null) {
            data = new LinkedHashMap<>();
        }

        if (errmsg == null) {
            errmsg = "";
        }

        putAll(data);
        setData("errcode", errcode);
        setData("errmsg", errmsg);
        //ID 或者 openid
        setData("id", "");
        //房间号
        setData("room_id", "");
        //行为
        //1:发消息
        //10:创建房间
        //11:加入房间
        setData("action", 0);
        //业务事件，业务控制内容
        setData("event", "");

        setData("api_date", XDate.toDateTimeString());
    }

    static public NettyMsg getR(String roomId) {
        return NettyMsg.getR(roomId, 0, "");
    }

    static public NettyMsg getR(String roomId, Integer errcode) {
        return NettyMsg.getR(roomId, errcode, "");
    }

    static public NettyMsg getR(String roomId, Integer errcode, String errmsg) {
        NettyMsg nettyMsg = new NettyMsg(errcode, errmsg, null);
        nettyMsg.setErrCode(errcode);
        nettyMsg.setErrMsg(errmsg);
        nettyMsg.setRoom_id(roomId);
        return nettyMsg;
    }


    static public NettyMsg parse(String msg) {
        NettyMsg entity = NettyMsg.getR("");
        try {
            Map mapMsg = XJson.parseObject(msg, Map.class);
            XBean.fromMap(mapMsg, entity);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
        }

        return entity;
    }

    static public NettyMsg fromR(XReturn r) {
        return NettyMsg.getR("", r.getErrCode(), r.getErrMsg());
    }


    public String getId() {
        return getData("id", null);
    }

    public void setId(String id) {
        setData("id", id);
    }

    public String getRoomId() {
        return getData("room_id", null);
    }

    public void setRoom_id(String roomId) {
        setData("room_id", roomId);
    }

    public Integer getAction() {
        return getData("action", 0);
    }

    public void setAction(Integer action) {
        setData("action", action);
    }

    public String getEvent() {
        return getData("event", null);
    }

    public void setEvent(String event) {
        setData("event", event);
    }

    public void setToken(String token) {
        setData("token", token);
    }

    /**
     * 事件json转实体
     *
     * @param clazz
     * @param <T>
     */
    public <T> T paresEvent(Class<T> clazz) {
        return XJson.parseObject(getEvent(), clazz);
    }
}
